package com.yjw.zookeeper.native_api;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class WatcherDemo {

    public static void main(String[] args) {
        ZooKeeper zooKeeper = null;
        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            zooKeeper = new ZooKeeper("192.168.202.18:2181,192.168.202.49:2181,192.168.202.50:2181",
                    4000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    // 收到服务端响应时间，连接成功
                    if (Event.KeeperState.SyncConnected == event.getState()) {
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();

            zooKeeper.create("/zk-persis", "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            // 注册事件机制
            final ZooKeeper finalZookeeper = zooKeeper;

            Stat stat = zooKeeper.exists("/zk-persis", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println(event.getType() + " -> " + event.getPath());
                    try {
                        finalZookeeper.exists("/zk-persis", new Watcher() {
                            @Override
                            public void process(WatchedEvent event) {
                                System.out.println(event.getType() + " -> " + event.getPath());
                            }
                        });
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 触发事件
            stat = zooKeeper.setData("/zk-persis", "1".getBytes(), stat.getVersion());

            Thread.sleep(1000);

            zooKeeper.delete("/zk-persis", stat.getVersion());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } finally {
            if (zooKeeper != null) {
                try {
                    zooKeeper.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
